package com.jd.system.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.jd.system.entity.User;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

import static com.google.zxing.client.j2se.MatrixToImageConfig.BLACK;
import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;

@RestController
public class Test2Controller {

    @ResponseBody
    @RequestMapping(value = "/mycode", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String mycode(@RequestBody User user) {
        String url = "http://xz8090.com:8090/his?n1="+user.getN1()+"&n2="+user.getN2()+"&n3="+user.getN3()
                +"&n4="+user.getN4()+"&n5="+user.getN5()+"&n6="+user.getN6();
        System.out.println("mycode:"+url);
        try {
            return generateQRCodeImage(url,780,780);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        BufferedImage image = deleteWhite(bitMatrix); //去白边的话加这一行

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ImageIO.write(image, "png", outputStream);

        //转换为base64
        Base64.Encoder encoder1 = Base64.getEncoder();
        String qrCodeImage = "data:image/jpeg;base64,"+encoder1.encodeToString(outputStream.toByteArray());

        return qrCodeImage;
    }

    //去白边的话，调用这个方法
    private static BufferedImage deleteWhite(BitMatrix matrix) {
        int[] rec = matrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;

        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (matrix.get(i + rec[0], j + rec[1]))
                    resMatrix.set(i, j);
            }
        }

        int width = resMatrix.getWidth();
        int height = resMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, resMatrix.get(x, y) ? BLACK
                        : WHITE);
            }
        }
        return image;
    }

}
